if (kendo.support.browser.webkit || kendo.support.browser.mozilla || (kendo.support.browser.msie &&  kendo.support.browser.version >= 10)) {
    (function ($, undefined) {

        var devices = [ "ios7", "ios", "android", "blackberry", "wp", "flat" ], CtrlDown = false,
            originalToggle, visibleOSes, wasActive, helpRead,
            deviceClasses = $.map(devices, function (value) { return ".km-" + value; }),
            extend = $.extend, importWindow, exportWindow,
            each = $.each,
            dragging = false,
            globalUndoBuffer = [],
            globalRedoBuffer = [],
            click = kendo.support.touch ? "touchend" : "click",
            defaultCSS = { cursor: "default", background: "", color: "", "border-color": "", font: "", "text-shadow": "" },
            browsers = [ "-webkit-", "-moz-", "-ms-" ],
            propertyTargets = {
                color: [ "background-color", "color", "border-color" ],
                gradient: [ "background-image" ],
                pattern: [ "background-image" ],
                font: [ "font" ]
            },
            packages = {
                color: [ "background-color" ],
                "background-color": [ "background-color" ],
                "border-color": [ "background-color" ],
                "background-image": [ "background-image", "background-repeat", "background-position" ],
                gradient: [ "background-image" ],
                pattern: [ "background-image", "background-repeat", "background-position" ],
                font: [ "font-family", "font-size", "font-weight", "font-style", "line-height", "text-shadow" ]
            },
            tools = {
                color: new Color(),
                gradient: new Gradient(),
                pattern: {
                    get: function () { return this.result; },
                    set: function (result) { this.result = result; return this; }
                },
                font: {
                    get: function () { return this.result; },
                    set: function (result) { this.result = result; return this; }
                }
            },
            engineTool = null,
            backgroundSplitRegExp = /\s*,\s*(?=-|url)/i,
            properties = propertyTargets.color.concat(propertyTargets.gradient, propertyTargets.pattern, propertyTargets.font),
            TRANSITION = kendo.support.transitions.css + "transition",
            fillSvg = 'url(\'data:image/svg+xml;utf-8,<svg version="1.1" xmlns="http:%2F%2Fwww.w3.org%2F2000%2Fsvg" xmlns:xlink="http:%2F%2Fwww.w3.org%2F1999%2Fxlink" width="28" height="38"><linearGradient id="shadow" gradientUnits="userSpaceOnUse" x1="14" y1="25" x2="14" y2="0"><stop offset="0" style="stop-color:rgba(0,0,0,.3)"%2F><%2FlinearGradient><path fill="url(%23shadow)" d="M26.667,15.236c0-6.996-5.671-12.667-12.667-12.667c-6.995,0-12.667,5.672-12.667,12.667c0,4.78,2.651,8.938,6.562,11.097 C10.695,31.772,14,36.95,14,36.95s3.305-5.178,6.105-10.617C24.017,24.175,26.667,20.017,26.667,15.236z"%2F><path fill="%23FFF" d="M26.667,13.819c0-6.996-5.671-12.667-12.667-12.667c-6.995,0-12.667,5.672-12.667,12.667 c0,4.78,2.651,8.938,6.562,11.097C10.695,30.355,14,35.533,14,35.533s3.305-5.178,6.105-10.617 C24.017,22.758,26.667,18.6,26.667,13.819z"%2F><linearGradient id="ID" gradientUnits="userSpaceOnUse" x1="50%" y1="0" x2="50%" y2="28"><stop offset="0"%2F><%2FlinearGradient><circle fill="url(%23sq)" cx="14" cy="14" r="11"%2F><pattern id="sq" patternUnits="userSpaceOnUse" x="0" y="0" width="14" height="14" patternTransform="rotate(45)"><rect fill="%23888" x="0" y="0" width="14" height="14"%2f><rect fill="%23666" x="0" y="0" width="7" height="7"%2f><rect fill="%23666" x="7" y="7" width="7" height="7"%2f></pattern><circle fill="url(%23ID)" cx="14" cy="14" r="11"%2F><path fill="rgba(0,0,0,.3)" d="M14,4.403c5.616,0,10.189,4.413,10.473,9.958c0.009-0.18,0.027-0.359,0.027-0.542c0-5.799-4.701-10.5-10.5-10.5 S3.5,8.021,3.5,13.82c0,0.183,0.018,0.361,0.027,0.542C3.811,8.816,8.384,4.403,14,4.403z"%2F><linearGradient id="gr1" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="100%" y2="100%"><stop offset=".25" stop-color="%23666"%2F><stop offset=".25" stop-opacity="0"%2F><%2FlinearGradient><linearGradient id="gr2" gradientUnits="userSpaceOnUse" x1="0" y1="100%" x2="0" y2="100%"><stop offset=".25" stop-color="%23666"%2F><stop offset=".25" stop-opacity="0"%2F><%2FlinearGradient><linearGradient id="gr3" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="100%" y2="100%"><stop offset=".75" stop-opacity="0"%2F><stop offset=".75" stop-color="%23666"%2F><%2FlinearGradient><linearGradient id="gr4" gradientUnits="userSpaceOnUse" x1="0" y1="100%" x2="0" y2="100%"><stop offset=".75" stop-opacity="0"%2F><stop offset=".75" stop-color="%23666"%2F><%2FlinearGradient><%2Fsvg>\')',
            ie10fillSvg = "<div class='ie10hint'>" + fillSvg.replace("url(\'data:image/svg+xml;utf-8,", "").replace(/\)$/, "").replace(/%2f/gi, "/").replace(/%23/gi, "#") + "</div>",
            cursorSvg = fillSvg + ' 14 37, crosshair',
            defaultColor = '<circle fill="url(%23ID)" cx="14" cy="14" r="11"%2F>',
            defaultIE10Color = '<circle fill="url(#ID)" cx="14" cy="14" r="11"/>',
            defaultPattern = '<circle fill="url(%23pattern)" cx="14" cy="14" r="11"%2F><pattern id="pattern" patternUnits="userSpaceOnUse" x="0" y="0" width="8" height="8"><image x="0" y="0" width="8" height="8" xlink:href="##" clip-path="url(%23clipmask)" %2F><%2Fpattern>',
            defaultFont = '<text x="14" y="17" width="28" text-anchor="middle" fill="%23fff" style="##">Aa<%2Ftext>',
            defaultStop = '<linearGradient id="ID" gradientUnits="userSpaceOnUse" x1="50%" y1="0" x2="50%" y2="28"><stop offset="0"%2F><%2FlinearGradient>',
            defaultIE10Stop = '<linearGradient id="ID" gradientUnits="userSpaceOnUse" x1="50%" y1="0" x2="50%" y2="28"><stop offset="0"/></linearGradient>',
            ui = kendo.ui,
            Widget = ui.Widget,
            applications = {},
            counter = 1,
            clones = extend([], devices),
            widgetList = {
                listitemactiveicon: {
                    name: "Active List Icon",
                    selector: ".km-state-active .km-listview-link .km-icon",
                    whitelist: [ "color", "background-image" ]
                },
                activeicon: {
                    name: "Active Icon",
                    selector: ".km-state-active span.km-icon",
                    whitelist: [ "color", "background-image" ]
                },
                icon: {
                    name: "Icon",
                    selector: ".km-icon",
                    whitelist: [ "color", "background-image", "width", "height" ]
                },
                activetext: {
                    name: "Active Text",
                    selector: ".km-active-state .km-text",
                    whitelist: [ "color" ],
                    blacklist: ".km-android .km-tabstrip .km-text, .km-blackberry .km-tabstrip .km-text, .km-meego .km-tabstrip .km-text"
                },
                text: {
                    name: "Text",
                    selector: ".km-text",
                    whitelist: [ "color" ],
                    blacklist: ".km-android .km-tabstrip .km-text, .km-blackberry .km-tabstrip .km-text, .km-meego .km-tabstrip .km-text"
                },
                grouptitleinset: {
                    name: "Group Title Inset",
                    selector: ".km-listgroupinset .km-group-title",
                    whitelist: [ "color", "background-color", "background-image" ]
                },
                grouptitle: {
                    name: "Group Title",
                    selector: ".km-listgroup .km-group-title",
                    whitelist: [ "color", "background-color", "background-image" ]
                },
                viewtitle: {
                    name: "View Title",
                    selector: ".km-view-title > *",
                    whitelist: [ "color" ]
                },
                listitemactivelink: {
                    name: "Active List Link",
                    selector: ".km-state-active .km-listview-link",
                    whitelist: [ "background-color", "background-image", "border-radius", "color", "border-color" ]
                },
                listitem: {
                    name: "List Item",
                    selector: ".km-list > li",
                    activeSelector: ".km-state-active",
                    whitelist: [ "background-color", "background-image", "border-radius", "color", "border-color" ]
                },
                scrollitem: {
                    name: "ScrollView Item",
                    selector: ".km-scrollview > div > *",
                    whitelist: [ "width", "height" ]
                },
                switchback: {
                    name: "Switch Background",
                    selector: ".km-switch-background",
                    whitelist: [ "background-color", "background-image" ]
                },
                switchcontainer: {
                    name: "Switch Container",
                    selector: ".km-switch-container",
                    whitelist: [ "background-color", "background-image" ]
                },
                switchhandleon: {
                    name: "Active Switch Handle",
                    selector: ".km-android .km-switch-on .km-switch-handle",
                    whitelist: [ "border-color" ]
                },
                switchhandleoff: {
                    name: "Inactive Switch Handle",
                    selector: ".km-android .km-switch-off .km-switch-handle",
                    whitelist: [ "border-color" ]
                },
                switchhandle: {
                    name: "Switch Handle",
                    selector: ".km-switch-handle",
                    whitelist: [ "width", "height", "background-color", "background-image" ]
                },
                switchon: {
                    name: "Switch On Label",
                    selector: ".km-switch-label-on",
                    whitelist: [ "left", "width", "height", "color" ]
                },
                switchoff: {
                    name: "Switch Off Label",
                    selector: ".km-switch-label-off",
                    whitelist: [ "left", "width", "height", "color" ]
                },
                switcher: {
                    name: "Switch",
                    selector: ".km-switch",
                    activeSelector: ".km-switch-on",
                    whitelist: [ "width", "height" ],
                    children: [ "switchback", "switchhandle", "switchon", "switchoff" ]
                },
                buttongroup: {
                    selector: ".km-button-group",
                    whitelist: [ "box-shadow", "border-radius" ],
                    children: [ "button" ]
                },
                scrollview: {
                    name: "ScrollView",
                    selector: ".km-scrollview",
                    whitelist: [ "background-color", "background-image", "box-shadow" ],
                    children: [ "scrollitem" ]
                },
                activebutton: {
                    name: "Active Button",
                    selector: ".km-button.km-state-active",
                    activeSelector: ".km-state-active",
                    whitelist: [ "background-color", "background-image", "border-color" ]
                },
                button: {
                    name: "Button",
                    selector: ".km-button",
                    activeSelector: ".km-state-active",
                    whitelist: [ "background-color", "background-image", "border-color" ],
                    children: [ "icon", "text" ]
                },
                navbar: {
                    name: "NavBar",
                    selector: ".km-navbar",
                    whitelist: [ "background-color", "background-image", "font" ],
                    children: [ "button", "viewtitle" ]
                },
                listview: {
                    name: "ListView",
                    selector: ".km-list",
                    whitelist: [ "border-color" ],
                    children: [ "icon", "button", "switch", "listitem", "grouptitle" ]
                },
                content: {
                    name: "View Content",
                    selector: ".km-content",
                    whitelist: [ "background-color", "color", "background-image", "font" ],
                    children: [ "button", "listview", "scrollview", "switch", "buttongroup" ]
                },
                tabstrip: {
                    name: "TabStrip",
                    selector: ".km-tabstrip",
                    whitelist: [ "background-color", "background-image", "border-color", "border-width", "border-style", "font" ],
                    children: [ "button" ]
                },
                view: {
                    name: "View",
                    selector: ".km-view",
                    whitelist: [ "background-color" ],
                    children: [ "navbar", "content", "tabstrip", "loader" ]
                },
                ios: {
                    selector: ".km-ios"
                },
                ios7: {
                    selector: ".km-ios7"
                },
                android: {
                    selector: ".km-android"
                },
                blackberry: {
                    selector: ".km-blackberry"
                },
                wp: {
                    selector: ".km-wp"
                },
                flat: {
                    selector: ".km-flat"
                },
                meego: {
                    selector: ".km-meego"
                }
            },
            pickers = {},

            defaults = {
                color: [
                    { "background-color": "#c5007c" },
                    { "background-color": "#6300a5" },
                    { "background-color": "#0010a5" },
                    { "background-color": "#0064b5" },
                    { "background-color": "#00a3c7" },
                    { "background-color": "#0fad00" },
                    { "background-color": "#8cc700" },
                    { "background-color": "#ff0" },
                    { "background-color": "#fec500" },
                    { "background-color": "#ff9400" },
                    { "background-color": "#f60" },
                    { "background-color": "#f00" },

                    { "background-color": "#fff" },
                    { "background-color": "#e5e5e5" },
                    { "background-color": "#ccc" },
                    { "background-color": "#b2b2b2" },
                    { "background-color": "#999" },
                    { "background-color": "#7f7f7f" },
                    { "background-color": "#666" },
                    { "background-color": "#4c4c4c" },
                    { "background-color": "#333" },
                    { "background-color": "#191919" },
                    { "background-color": "#000" },
                    { "background-color": "none" }
                ],

                gradient: [
                    { "background-image": "linear-gradient(top, #fff, rgba(255,255,255,.2) 50%, rgba(255,255,255,.3) 50%, rgba(255,255,255,.7))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.2), rgba(255,255,255,.4) 50%, rgba(255,255,255,.5) 50%, rgba(255,255,255,.8))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.2), rgba(255,255,255,.35) 50%, rgba(255,255,255,.45) 50%, rgba(255,255,255,.4))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.2), rgba(255,255,255,.4) 50%, rgba(255,255,255,.45) 50%, rgba(255,255,255,.4))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.6), rgba(255,255,255,.35) 50%, rgba(255,255,255,.4) 50%, rgba(255,255,255,.6))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.4), rgba(255,255,255,.6))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.2), rgba(255,255,255,.8))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.5), rgba(255,255,255,.2) 50%, rgba(255,255,255,.5))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.5), rgba(255,255,255,.2) 73%, rgba(255,255,255,.5))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.2), rgba(255,255,255,.5) 73%, rgba(255,255,255,.2))" },
                    { "background-image": "linear-gradient(top, rgba(255,255,255,.2), rgba(255,255,255,.35) 12%, rgba(255,255,255,.65) 40%, rgba(255,255,255,.4) 80%, rgba(255,255,255,.6))" },

                    { "background-image": "linear-gradient(top, rgba(0,0,0,.2), rgba(0,0,0,.4) 50%, rgba(0,0,0,.5) 50%, rgba(0,0,0,.8))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.2), rgba(0,0,0,.35) 50%, rgba(0,0,0,.45) 50%, rgba(0,0,0,.4))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.2), rgba(0,0,0,.4) 50%, rgba(0,0,0,.45) 50%, rgba(0,0,0,.4))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.6), rgba(0,0,0,.35) 50%, rgba(0,0,0,.4) 50%, rgba(0,0,0,.6))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.4), rgba(0,0,0,.6))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.2), rgba(0,0,0,.8))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.5), rgba(0,0,0,.2) 50%, rgba(0,0,0,.5))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.5), rgba(0,0,0,.2) 73%, rgba(0,0,0,.5))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.2), rgba(0,0,0,.5) 73%, rgba(0,0,0,.2))" },
                    { "background-image": "linear-gradient(top, rgba(0,0,0,.2), rgba(0,0,0,.35) 12%, rgba(0,0,0,.65) 40%, rgba(0,0,0,.4) 80%, rgba(0,0,0,.6))" },
                    { "background-image": "none" }
                ],

                pattern: [
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },

                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "url()" },
                    { "background-image": "none" }
                ],

                font: [
                    { font: "0.9em/normal HelveticaNeue, Roboto, 'Myriad Pro', 'Nokia Pure', Arial, sans-serif", "text-shadow" : "none" },
                    { font: "1em/normal HelveticaNeue, Roboto, 'Myriad Pro', 'Nokia Pure', Arial, sans-serif", "text-shadow" : "none" },
                    { font: "italic 1em/1.2em HelveticaNeue, Roboto, 'Myriad Pro', 'Nokia Pure', Arial, sans-serif", "text-shadow" : "none" },
                    { font: "0.9em/normal HelveticaNeue, Roboto, 'Myriad Pro', 'Nokia Pure', Arial, sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "1em/normal HelveticaNeue, Roboto, 'Myriad Pro', 'Nokia Pure', Arial, sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "italic 1em HelveticaNeue, Roboto, 'Myriad Pro', 'Nokia Pure', Arial, sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "0.9em/normal Roboto, HelveticaNeue, sans-serif", "text-shadow" : "none" },
                    { font: "1em/normal Roboto, HelveticaNeue, sans-serif", "text-shadow" : "none" },
                    { font: "italic 1em Roboto, HelveticaNeue, sans-serif", "text-shadow" : "none" },
                    { font: "0.9em/normal Roboto, HelveticaNeue, sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "1em/normal Roboto, HelveticaNeue, sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "italic 1em Roboto, HelveticaNeue, sans-serif", "text-shadow" : "0 -1px #000" },

                    { font: "0.9em/normal 'Lucida Sans Unicode', 'Lucida Grande', sans-serif", "text-shadow" : "none" },
                    { font: "1em/normal 'Lucida Sans Unicode', 'Lucida Grande', sans-serif", "text-shadow" : "none" },
                    { font: "italic 1em 'Lucida Sans Unicode', 'Lucida Grande', sans-serif", "text-shadow" : "none" },
                    { font: "0.9em/normal 'Lucida Sans Unicode', 'Lucida Grande', sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "1em/normal 'Lucida Sans Unicode', 'Lucida Grande', sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "italic 1em 'Lucida Sans Unicode', 'Lucida Grande', sans-serif", "text-shadow" : "0 -1px #000" },
                    { font: "0.9em/normal Arial, Helvetica, sans-serif", "text-shadow" : "none" },
                    { font: "1em/normal Arial, Helvetica, sans-serif", "text-shadow" : "none" },
                    { font: "italic 1em Arial, Helvetica, sans-serif", "text-shadow" : "0 -1px #000" },
                    { "font-family": "inherit", "font-size": "inherit", "font-weight": "inherit", "font-style": "inherit", "line-height": "inherit", "text-shadow" : "inherit" }
                ]
            },

            i = 0,
            events = {
                color: {
                    cursorOffset: {
                        left: -50,
                        top: -38
                    },
                    hint: function (element) {
                        if (kendo.support.browser.msie) {
                            return $(ie10fillSvg.replace(defaultIE10Color, '<circle fill="' + element.css("background-color") + '" cx="14" cy="14" r="11"/>'));
                        } else {
                            return kendo.support.touch ?
                                $("<div " + (kendo.support.browser.msie ? "class='iehint'" : "") + "style='width: 28px; height: 38px'/>")
                                    .css("background-image", fillSvg.replace(defaultColor, '<circle fill="' + element.css("background-color") + '" cx="14" cy="14" r="11"%2F>'))
                                : undefined;
                        }
                    },
                    dragstart: function () {
                        var element = this.element,
                            color = element.css("background-color"),
                            doc = document.documentElement;

                        dragging = true;
                        element.data("property", "color");
                        element.data("background-color", tools.color.compress(color));

                        $(doc).addClass("drop-override");
                        if (!kendo.support.touch) {
                            doc.style.cssText = "cursor: " + (kendo.support.browser.msie ? "none" : cursorSvg.replace(defaultColor, '<circle fill="' + color + '" cx="14" cy="14" r="11"%2F>'));
                        }
                        addRecentItem(element, "color");
                    },
                    dragend: function () {
                        var doc = document.documentElement;

                        dragging = false;
                        widgetTarget.hide();

                        $(doc).removeClass("drop-override");
                        doc.style.cssText = "";
                    }
                }
            },
            widgetTarget = $("<div class='widgetTarget'><div><div /><div /></div><span /><div><span /></div></div>").appendTo(document.body),

            StyleEngine = Widget.extend({
                init: function (element, options) {
                    var that = this, key;

                    Widget.fn.init.call(that, element, options);
                    element = that.element;
                    options = that.options;

                    that.object = {};
                    that.undoBuffer = [];
                    that.redoBuffer = [];

                    if (options.restoreFromStorage) {
                        if (localStorage && localStorage.length) {
                            try {
                                for (var i = 0; i < localStorage.length; i++){
                                    key = localStorage.key(i);
                                    if (key.indexOf(".km-" + options.platform) === 0) {
                                        that.object[key] = JSON.parse(localStorage.getItem(key));
                                    }
                                }
                            } catch(err) {}
                        }
                    }

                    that.styleElement = $("<style scoped>\n" + that.getCSS() + "</style>").insertBefore(element);
                },
                options: {
                    name: "StyleEngine",
                    restoreFromStorage: false,
                    platform: ""
                },
                cleanse: function() {
                    var that = this, idx;

                    for (idx in that.object) {
                        if (!that.object[idx]) {
                            delete that.object[idx];
                        }
                    }
                },
                populate: function(styles) {
                    var that = this, style;

                    that.object = kendo.deepExtend(that.object, styles);
                    that.cleanse();

                    style = $("<style scoped>\n" + that.getCSS() + "</style>").insertAfter(that.styleElement);

                    that.styleElement.remove();
                    that.styleElement = style;
                },
                getElementSelector: function (element, agnostic) {
                    var output = "", widget,
                        parents = element.parentsUntil(agnostic ? ".km-pane" : ".km-root");

                    $(parents.add(element).get().reverse()).each(function (idx, value) {
                        widget = matchWidget(value);
                        if (widget && !(new RegExp(widget.selector + "\\s" + (widget.activeSelector ? "|" + widget.activeSelector + "\\s" : "")).test(output))) {
                            output = widget.selector + " " + output;
                        }
                    });

                    return output.substr(0, output.length-1);
                },
                update: function(element, styles, selector) {
                    element = $(element);
                    var that = this, style = {},
                        output = selector || that.getElementSelector(element),
                        undoItem = {};

                    if (output) {
                        undoItem[output] = kendo.deepExtend({}, that.object[output]);
                        that.undoBuffer.push(undoItem);

                        if (this.object[output]) {
                            style[output] = kendo.deepExtend(this.object[output], styles);
                        } else {
                            style[output] = styles;
                        }
                        that.store(output, style[output]);

                        that.populate(style);

                        if (globalUndoBuffer) {
                            globalUndoBuffer.push(that);
                        }
                    }
                },
                undo: function() {
                    var that = this, key, redoItem = {},
                        item = that.undoBuffer.pop();

                    if (item) {
                        key = Object.keys(item)[0];

                        redoItem[key] = kendo.deepExtend({}, that.object[key]);
                        that.redoBuffer.push(redoItem);
                        if (globalRedoBuffer) {
                            globalRedoBuffer.push(that);
                        }

                        that.store(key, item[key]);

                        if (!kendo.size(item[key])) {
                            item[key] = "";
                        }

                        that.populate(item);
                    }
                },
                redo: function() {
                    var that = this, key, undoItem = {},
                        item = that.redoBuffer.pop();

                    if (item) {
                        key = Object.keys(item)[0];

                        undoItem[key] = kendo.deepExtend({}, that.object[key]);
                        that.undoBuffer.push(undoItem);
                        if (globalUndoBuffer) {
                            globalUndoBuffer.push(that);
                        }

                        that.store(key, item[key]);

                        if (!kendo.size(item[key])) {
                            item[key] = "";
                        }

                        that.populate(item);
                    }
                },
                getCSS: function () {
                    var object = this.object, output = "";

                    for (var i in object) {
                        output += i + " {\n";
                        for (var j in object[i]) {
                            output += "    " + j + ": " + object[i][j] + ";\n";
                        }
                        output += "}\n";
                    }

                    return output;
                },
                getFullCSS: function () {
                    var object = this.object, output = "", outputs, backgrounds, firstLetter;

                    for (var i in object) {
                        output += i + " {\n";
                        for (var j in object[i]) {
                            if (j == "background-image") {
                                backgrounds = object[i][j].split(backgroundSplitRegExp);
                                outputs = [];
                                browsers.forEach(function () {
                                    outputs.push([]);
                                });

                                backgrounds.forEach(function (value) {
                                    firstLetter = value[0].toLowerCase();

                                    if (firstLetter != "u" && firstLetter != "n") {
                                        tools.gradient.set(value).get(browsers).forEach(function (val, idx) {
                                            outputs[idx].push(val);
                                        });
                                    } else {
                                        browsers.forEach(function (val, idx) {
                                            outputs[idx].push(value);
                                        })
                                    }
                                });

                                browsers.forEach(function (val, idx) {
                                    output += "    " + j + ": " + outputs[idx].join(",") + ";\n";
                                });
                            } else {
                                output += "    " + j + ": " + object[i][j] + ";\n";
                            }
                        }
                        output += "}\n";
                    }

                    return output;
                },
                mixBackground: function (css, element, replace, forceUrl) {
                    var that = this, idx, imageHash, repeats, url, comma, grPosition, grRepeat,
                        color = element.css("background-color"),
                        backgrounds = [ element.css("background-image").split(backgroundSplitRegExp), css["background-image"].split(backgroundSplitRegExp) ],
                        backSplits = [ { gradient: [], url: [] }, { gradient: [] }],
                        position = css["background-position"],
                        repeat = css["background-repeat"];

                    position = position ? position.substring(position.indexOf(",") + 1) : "";
                    repeat = repeat ? repeat.substring(repeat.indexOf(",") + 1) : "";

                    backgrounds.forEach(function (val, idx) {
                        val.forEach(function (value) {
                            if (value[0].toLowerCase() == "u" || (forceUrl && value.trim() == "none")) {
                                backSplits[0].url = [ value ];
                            } else {
                                if (!forceUrl && value.trim() == "none") {
                                    backSplits[0].gradient = [ "none" ];
                                } else {
                                    backSplits[idx].gradient.push( value );
                                }
                            }
                        });
                    });

                    idx = -1;
                    if (backSplits[1].gradient[0]) {
                        imageHash = that.createHash(backSplits[1].gradient[0]);
                        backSplits[0].gradient.forEach(function (value, i) {
                            if (that.createHash(value) == imageHash) {
                                idx = i;
                            }
                        });
                    }

                    if (replace && backSplits[1].gradient[0]) { idx = 0; }

                    if (idx > -1) {
                        backSplits[0].gradient[idx] = backSplits[1].gradient[0];
                    } else if (backSplits[0].gradient.length < 4 && backSplits[1].gradient[0]) {
                        backSplits[0].gradient.splice(0, 0, backSplits[1].gradient[0]);
                    }

                    repeats = new Array(backSplits[0].gradient.length+1);
                    grPosition = repeats.join("0 0,");
                    grRepeat = repeats.join("repeat,");
                    url = backSplits[0].url[0];
                    comma = (url ? "," :"");

                    return {
                        "background-color": color,
                        "background-image": (backSplits[0].gradient.length ? backSplits[0].gradient.join(",") + comma : "") + (url ? url : ""),
                        "background-position": grPosition.substr(0, grPosition.length - 1) + comma  + (url ? position : ""),
                        "background-repeat": grRepeat.substr(0, grRepeat.length - 1) + comma + (url ? repeat : "")
                    }
                },
                createHash: function(str) {
                    var hash = 0, i, len = str.length;

                    if (!len) {
                        return hash;
                    }

                    for (i = 0; i < len; i++) {
                        hash = ((hash << 5) - hash) + str.charCodeAt(i);
                        hash = hash & hash;
                    }

                    return hash;
                },
                store: function(property, obj) {
                    if (localStorage) {
                        try {
                            localStorage.setItem(property, JSON.stringify(obj));
                        } catch(err) {}
                    }
                },
                retrieve: function (property) {
                    if (localStorage && localStorage.length) {
                        try {
                            return JSON.parse(localStorage.getItem(property));
                        } catch(err) {}
                    }
                    return {};
                },
                reset: function () {
                    var that = this, key, style;

                    that.object = {};

                    style = $("<style scoped>\n" + that.getCSS() + "</style>").insertAfter(that.styleElement);

                    that.styleElement.remove();
                    that.styleElement = style;

                    if (that.options.restoreFromStorage) {
                        if (localStorage && localStorage.length) {
                            for (var i = 0; i < localStorage.length; i++){
                                key = localStorage.key(i);
                                if (key.indexOf(".km-" + that.options.platform) !== -1) {
                                    localStorage.removeItem(key);
                                    i--;
                                }
                            }
                        }
                    }
                }
            });

        kendo.ui.plugin(StyleEngine);

        if (localStorage) {
            try {
                helpRead = localStorage.getItem("helpRead");

                if (!helpRead) {
                    var help = $("<div class='help'><div><div class='closeHelp'></div></div></div>").appendTo(document.body);
                    $(".closeHelp").on(click, function () {
                        try {
                            localStorage.setItem("helpRead", true);
                            help.remove();
                        } catch(err) {}
                    });
                }

                visibleOSes = JSON.parse(localStorage.getItem("visibility"));
                visibleOSes.forEach(function (value) {
                    document.getElementById(value).checked = "checked";
                });
            } catch(err) {
                visibleOSes = [ "ios7box", "androidbox", "blackberrybox", "wpbox" ];
                visibleOSes.forEach(function (value) {
                    document.getElementById(value).checked = "checked";
                });
            }
        }

        window.URL = window.webkitURL || window.mozURL || window.URL;
        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;

        extend(events, {
            gradient: extend({}, events.color, {
                hint: function (element) {
                    if (kendo.support.browser.msie) {
                        return $(ie10fillSvg.replace(defaultIE10Stop, tools.gradient.set(element.css("background-image")).get("svg")));
                    } else {
                        return kendo.support.touch ?
                            $("<div style='width: 28px; height: 38px'/>")
                                .css("background-image", fillSvg.replace(defaultStop, tools.gradient.set(element.css("background-image")).get("svg"))) :
                            undefined;
                    }
                },
                dragstart: function () {
                    var element = this.element,
                        gradient = element.css("background-image"),
                        doc = document.documentElement;

                    dragging = true;
                    element.data("property", "gradient");
                    element.data("background-image", tools.gradient.set(gradient).get());

                    $(doc).addClass("drop-override");
                    if (!kendo.support.touch) {
                        doc.style.cssText = "cursor: " + (kendo.support.browser.msie ? "none" : cursorSvg.replace(defaultStop, tools.gradient.get("svg")));
                    }
                    addRecentItem(element, "gradient");
                }
            }),
            pattern: extend({}, events.color, {
                hint: function (element) {
                    if (kendo.support.browser.msie) {
                        return $(ie10fillSvg.replace(defaultIE10Color, defaultPattern.replace("##", element.css("background-image").replace(/^url\("?|"?\)$/ig, ""))));
                    } else {
                        return kendo.support.touch ?
                            $("<div style='width: 28px; height: 38px'/>")
                                .css("background-image", fillSvg.replace(defaultColor, defaultPattern.replace("##", element.css("background-image").replace(/^url\("?|"?\)$/ig, "").replace("/", "%2F")))) :
                            undefined;
                    }
                },
                dragstart: function () {
                    var element = this.element,
                        pattern = element.css("background-image"),
                        doc = document.documentElement;

                    dragging = true;
                    element.data("property", "pattern");
                    element.data("background-image", pattern);

                    $(doc).addClass("drop-override");
                    if (!kendo.support.touch) {
                        doc.style.cssText = "cursor: " + (kendo.support.browser.msie ? "none" : cursorSvg.replace(defaultColor, defaultPattern.replace("##", pattern.replace(/^url\("?|"?\)$/ig, ""))));
                    }
                    addRecentItem(element, "pattern");
                }
            }),
            font: extend({}, events.color, {
                hint: function (element) {
                    if (kendo.support.browser.msie) {
                        return $(ie10fillSvg.replace(defaultIE10Color, defaultFont.replace("##", JSON.stringify(kendo.getComputedStyles(element[0], [ "font-family", "font-size", "font-weight", "font-style" ])).replace(/","/g, ";").replace(/"|{|}|'/g, "")).replace(/%2f/gi, "/")));
                    } else {
                        return kendo.support.touch ?
                            $("<div style='width: 28px; height: 38px'/>")
                                .css("background-image", fillSvg.replace(defaultColor, defaultFont.replace("##", JSON.stringify(kendo.getComputedStyles(element[0], [ "font-family", "font-size", "font-weight", "font-style" ])).replace(/","/g, ";").replace(/"|{|}|'/g, "")))) :
                            undefined;
                    }
                },
                dragstart: function () {
                    var element = this.element,
                        font = JSON.stringify(kendo.getComputedStyles(element[0], [ "font-family", "font-size", "font-weight", "font-style" ])).replace(/","/g, ";").replace(/"|{|}|'/g, ""),
                        doc = document.documentElement;

                    dragging = true;
                    element.data("property", "font");
                    element.data("font", element.css("font"));

                    $(doc).addClass("drop-override");
                    if (!kendo.support.touch) {
                        doc.style.cssText = "cursor: " + (kendo.support.browser.msie ? "none" : cursorSvg.replace(defaultColor, defaultFont.replace("##", font)));
                    }
                    addRecentItem(element, "font");
                }
            })
        });

        for (var idx in widgetList) {
            var children = widgetList[idx].children;
            if (children) {
                children.forEach(function (name) {
                    var item = widgetList[name];
                    if (item) { item.parents = [ idx ].concat(item.parents || []); }
                });
            }
        }

        function matchWidget(element, properties) {
            if ($(element).hasClass("km-root")) return false;

            var widget, props;

            for(var idx in widgetList) {
                widget = widgetList[idx];

                if (kendo.support.matchesSelector.call(element, widget.selector) && !kendo.support.matchesSelector.call(element, widget.blacklist)) {
                    if (properties && widget.whitelist) {
                        props = widget.whitelist.filter(function (value) { return properties.indexOf(value) !== -1 });
                        if (props.length) {
                            return kendo.deepExtend( { widget: idx, element: element, properties: props, idx: 0 }, widget );
                        }
                    } else {
                        return kendo.deepExtend( { widget: idx, element: element }, widget );
                    }
                }
            }

            return matchWidget(element.parentNode, properties);
        }

        function getPropertySelector(property) {
            var output = "", widget;

            for(var idx in widgetList) {
                widget = widgetList[idx];
                if (((widget.whitelist && widget.whitelist.indexOf(property) != -1) || !property) && widget.selector[0] != ">") {
                    output += widget.selector + ",";
                }
            }
            return output.substring(0, output.length-1);
        }

        function getWidgets(property) {
            var widget, qualifiedWhiteList, widgets = { selector: "" };

            if (typeof property == "string")
                property = [ property ];

            for(var idx in widgetList) {
                widget = widgetList[idx];
                qualifiedWhiteList = widget.whitelist ? widget.whitelist.filter(function (value) { return property.indexOf(value) != -1; }) : [];

                if (((widget.whitelist && qualifiedWhiteList.length) || !property.length) && widget.selector[0] != ">") {
                    widgets[idx] = widget;
                    widgets[idx].whitelist = qualifiedWhiteList;
                    widgets.selector += widget.selector + ",";
                }
            }

            widgets.selector = widgets.selector.substring(0, widgets.selector.length-1);

            return widgets;
        }

        window.globalUndo = function() {
            var lastEngine = globalUndoBuffer.pop();

            if (lastEngine) {
                lastEngine.undo();
            }
        };

        window.globalRedo = function() {
            var lastEngine = globalRedoBuffer.pop();

            if (lastEngine) {
                lastEngine.redo();
            }
        };

        // Wheel scrolling affects property chooser
        kendo.mobile.ui.Scroller.prototype._wheelScroll = function(e) {};

        // Override Kendo Pane bindToRouter to avoid URL breaks and bad refresh
        kendo.mobile.ui.Pane.prototype.bindToRouter = function(router) {
            var that = this,
                options = that.options,
                initial = options.initial,
                viewEngine = this.viewEngine;

            router.bind("init", function(e) {
                var url = e.url,
                    attrUrl = router.pushState ? url : "/";

                viewEngine.rootView.attr(kendo.attr("url"), attrUrl);

                if (url === "/" && initial) {
                    router.navigate(initial, true);
                    e.preventDefault(); // prevents from executing routeMissing, by default
                }
            });

            router.bind("routeMissing", function(e) {
                if (!that.historyCallback(e.url, e.params)) {
                    e.preventDefault();
                }
            });

            router.bind("same", function() {
                that.trigger("sameViewRequested");
            });
        };

        originalToggle = kendo.mobile.ui.ListView.prototype._toggle;

        kendo.mobile.ui.ListView.prototype._toggle = function(e) {
            if ((!dragging && "mousemove touchmove".indexOf(e.type) == -1) && "mouseleave touchcancel".indexOf(e.type) == -1) {
                if (e.type != kendo.support.mouseup) {
                    wasActive = $(e.currentTarget).closest("li").hasClass("km-state-active");
                    originalToggle(e);
                } else {
                    if (!wasActive) {
                        originalToggle(e);
                    }
                }
            }
        };

        $(".device").on("mouseenter", ".km-list > li > .km-listview-link, .km-list > li > .km-listview-label, .km-button", function(e) {
            wasActive = $(e.currentTarget).hasClass("km-state-active") || $(e.currentTarget).parent().hasClass("km-state-active");
        });

        kendo.mobile.ui.Button.prototype._deactivate = function (e) {
            if ((!dragging && e.type != kendo.support.mousemove) && e.type != kendo.support.mousecancel) {
                if (e.type !== kendo.support.mouseup) {
                    wasActive = $(e.currentTarget).closest(".km-button,.km-detail").hasClass("km-state-active");
                    $(e.target).closest(".km-button,.km-detail").addClass("km-state-active");
                } else {
                    if (!wasActive) {
                        $(e.target).closest(".km-button,.km-detail").removeClass("km-state-active");
                    }
                }
            }
        };
        function replaceIDs() {
            var id = this.id;
            this.id += counter;
            $(this).closest(".device").find("[href^=#" + id + "]").attr("href", "#" + this.id);
        }

        function replaceLayouts() {
            var that = $(this),
                newId = that.attr("data-id") + counter++;

            that.attr("data-id", newId);
            that.closest(".device").find("[data-layout]").attr("data-layout", newId);
        }

        clones.shift();
        each(clones.reverse(), function () {
            $("#ios7Device")
                .clone(true)
                .find("[id]") // Make sure there are no duplicate IDs.
                .each(replaceIDs)
                .end()
                .find("[data-id]")
                .each(replaceLayouts)
                .end()
                .attr("id", this.toString() + "Device")
                .insertAfter("#ios7Device");
        });

        $("#" + clones[0] + "Device [data-role=view]").attr("data-init", "initTargets");

        each(devices, function () {
            var that = this.toString(),
                deviceId = "#" + that + "Device",
                device = $(deviceId),
                checkbox = $("#" + that + "box")[0];

            applications[that] = new kendo.mobile.Application(device, {
                skin: that,
                platform: that,
                icon: {
                  "72x72" : "../content/mobilethemebuilder/images/Icon-72.png",
                  "144x144" : "../content/mobilethemebuilder/images/Icon2x.png"
                },
                updateDocumentTitle: false
            });
            engineTool = device.kendoStyleEngine({ restoreFromStorage: true, platform: that }).data("kendoStyleEngine");

            device.toggleClass("hiddenOS", !checkbox.checked);
        });

        pickers = {
            color: $(".recent-colors").kendoHSLPicker({ filter: ".drop" }).data("kendoHSLPicker"),
            gradient: $(".recent-gradients").kendoGradientPicker({ filter: ".drop", styleEngine: engineTool }).data("kendoGradientPicker"),
            pattern: $(".recent-patterns").kendoPatternPicker({ filter: ".drop", styleEngine: engineTool }).data("kendoPatternPicker"),
            font: $(".recent-fonts").kendoFontPicker({ filter: ".drop", styleEngine: engineTool }).data("kendoFontPicker")
        };

        window.initTargets = function() {
            setTimeout(function () {
                var whitelisted = false,
                    draggedElement, css, widget = false,
                    color = "transparent";

                $(document.documentElement).off("touchmove");

                $(".color-holder .drop").kendoDraggable(events.color);
                $(".gradient-holder .drop").kendoDraggable(events.gradient);
                $(".pattern-holder .drop").kendoDraggable(events.pattern);
                $(".font-holder .drop").kendoDraggable(events.font);

                function applyHint(element, target, pkg) {
                    var engine = target.parents(".device").data("kendoStyleEngine"), color;

                    css = kendo.getComputedStyles(element, pkg);

                    if (css["background-color"]) {
                        color = css["background-color"];
                        delete css["background-color"];
                        css[whitelisted] = color;
                    }

                    if (css["background-image"]) {
                        kendo.deepExtend(css, engine.mixBackground(css, target, true, $(element).attr("data-pattern") !== undefined));
                    }

                    if (draggedElement.hasClass("k-none") && css["font-family"]) {
                        packages.font.forEach(function (value) {
                            delete css[value];
                        });

                        kendo.deepExtend(css, defaults.font[defaults.font.length - 1]);
                    }

                    target.css(css);

                    widgetTarget
                        .children("div")
                        .last()
                        .children()
                        .text(whitelisted);
                }

                $(".device").on("DOMMouseScroll mousewheel", "*", function (e) {
                    if (!dragging) { return; }

                    if (widget) {
                        e.preventDefault();
                        e.stopImmediatePropagation();

                        var properties = widget.properties,
                            target = $(widget.element),
                            maxIndex = properties.length - 1;

                        widget.idx += (e.originalEvent.wheelDelta / 120 || e.originalEvent.detail / 3);
                        widget.idx < 0 && (widget.idx = maxIndex);
                        widget.idx > maxIndex && (widget.idx = 0);

                        target.css(defaultCSS);

                        whitelisted = widget.whitelist.indexOf(properties[widget.idx]) != -1 ? properties[widget.idx] : false;

                        if (!whitelisted) {
                            return;
                        }

                        applyHint(draggedElement[0], target, packages[properties[widget.idx]]);
                    }
                });

                $(".device").kendoDropTargetArea({
                    filter: getWidgets(properties).selector,
                    dragenter: function (e) {
                        draggedElement = $(e.draggable.element);

                        var properties = propertyTargets[draggedElement.data("property")];

                        widget = matchWidget(e.dropTarget[0], properties);
                        properties = widget.properties;

                        var target = $(widget.element),
                            offset = target.offset(),
                            height = target.outerHeight(),
                            widgetChildren = widgetTarget.children("div");

                        if (widget && widget.whitelist) {
                            whitelisted = widget.whitelist.indexOf(properties[widget.idx]) != -1 ? properties[widget.idx] : false;

                            if (!whitelisted) {
                                return;
                            }

                            applyHint(draggedElement[0], target, packages[whitelisted]);

                            widgetTarget
                                .show()
                                .css(TRANSITION, "all 100ms")
                                .css("display");

                            widgetTarget
                                .css({
                                    top: offset.top,
                                    left: offset.left
                                })
                                .children("span")
                                .text(widget.name);

                            widgetChildren
                                .width(target.outerWidth())
                                .css(TRANSITION, "all 100ms")
                                .last()
                                .css("top", height)
                                .end()
                                .css("display");

                            widgetChildren
                                .children("div")
                                .height(height)
                                .css(TRANSITION, "all 100ms")
                                .css("display");
                        }
                    },
                    dragleave: function () {
                        $(widget.element).css(defaultCSS);
                        widgetTarget.hide();
                    },
                    drop: function (e) {
                        if (!whitelisted) {
                            return;
                        }

                        var target = $(widget.element),
                            engines = $("#applyall")[0].checked ?
                                $.map(visibleOSes, function (value) { return $("#" + value.replace("box", "Device")).data("kendoStyleEngine"); }) :
                                [ target.parents(".device").data("kendoStyleEngine") ],
                            targetSelector = engines[0].getElementSelector(target, true);

                        target.css(defaultCSS);
                        widgetTarget.hide();

                        engines.forEach(function (value) {
                            var currentTarget = value.element.find(targetSelector);

                            if (css["background-image"]) {
                                kendo.deepExtend(css, value.mixBackground(css, currentTarget, true, draggedElement.attr("data-pattern") !== undefined));
                            }

                            value.update(currentTarget, css, ".km-" + value.options.platform + " " + targetSelector);
                        });
                    }
                });

                $(document).on({
                    keydown: function (e) { CtrlDown = e.which == 17; },
                    keyup: function (e) {
                        var Y = e.which == 89 || e.which == 121,
                            Z = e.which == 90 || e.which == 122;

                        if (e.ctrlKey && (Y || Z)) {
                            e.stopImmediatePropagation();
                            e.preventDefault();
                            if (e.shiftKey || Y) {
                                globalRedo();
                            } else {
                                globalUndo();
                            }
                        }
                        e.which == 17 && (CtrlDown = false);
                    }
                });

                $(".device").on(click, ".utility-active", function (e) {
                    var target = $(e.currentTarget),
                        width = target.outerWidth();

                    if (width - 20 < e.offsetX && e.offsetX < width && e.offsetY > 0 && e.offsetY < 20) {
                        e.stopImmediatePropagation();
                        e.preventDefault();
                    }
                });

            }, 200);
        };

        window.mobileAccountViewInit = function () {
            var listviews = this.element.find("ul.km-listview");

            this.element.find("[id^=settings-view]").kendoMobileButtonGroup({
                select: function() {
                    listviews.hide()
                             .eq(this.selectedIndex)
                             .show();
                },
                index: 0
            });
        };

        function addRecentItem(element, type) {
            element = $(element);

            var existing = $('.recent-' + type + 's [data-' + type + '="' + element.attr("data-" + type) + '"]');

            if (existing[0]) {
                existing
                    .addClass("k-state-active")
                    .trigger(click)
                    .siblings(".k-state-active")
                    .removeClass("k-state-active")
            } else {
                var recent = element.clone()
                    .prependTo(".recent-" + type + "s")
                    .addClass("k-state-active")
                    .siblings(".k-state-active")
                    .removeClass("k-state-active").end();

                recent.kendoDraggable(events[type]);
                pickers[type].popup.wrapper.addClass("k-static-shown");
                pickers[type].open(recent);

                recent.on(click, function (e) {
                    var that = $(this), item;

                    if (e.button == 0) {
                        that.addClass("k-state-active")
                            .siblings(".k-state-active")
                            .removeClass("k-state-active");
                    } else if (e.button == 1) {
                        if (this == pickers[type].target[0]) {
                            item = that.next();
                            !item[0] && (item = that.prev());

                            if (!item[0]) {
                                pickers[type].popup.wrapper.removeClass("k-static-shown");
                                pickers[type].close();
                            } else {
                                pickers[type].open(item);
                            }
                        }
                        that.remove();
                    }
                });
            }
        }

        ["color", "gradient", "pattern", "font"].forEach(function (type) {
            i = 0;
            while (defaults[type][i]) {
                var value = defaults[type][i], drop, style;

                if (value["background-image"]) {
                    value["background-image"] = tools[type].set(value["background-image"]).get();
                }

                if (value["background-color"]) {

                }

                drop = $('<div class="drop"></div>')
                        .css(value)
                        .insertBefore(".recent-" + type + "s")
                        .on(click, function () {
                            addRecentItem(this, type);
                        });

                style = JSON.stringify(kendo.getComputedStyles(drop[0], packages[type]));
                drop.attr("data-" + type, (type == "color" ? value["background-color"] : engineTool.createHash(style)));

                i++;

                if (!(i % (type != "gradient" && type != "font" ? 12 : 11))) {
                   $("<br />").insertBefore(".recent-" + type + "s");
                }
            }

            $("." + type + "-holder .drop:last").addClass("k-none");
            kendo.wrap(pickers[type].popup.element).addClass("k-static-picker k-static-" + type);
        });

        $(".tools").kendoTabStrip({
            animation: {
                open: {
                    effects: "fade:in"
                }
            },
            select: function (e) {

            }
        });

        $("body").css("visibility", "visible");

        $(".optionsSheet input").on("change", function () {
            $("#" + this.id.replace("box", "Device")).toggleClass("hiddenOS", !this.checked);

            visibleOSes = $(this)
                            .parents(".optionsSheet")
                            .find("label")
                            .prev(":checked")
                            .map(function() {
                                return this.id;
                            }).toArray();

            if (localStorage && localStorage.length) {
                try {
                    localStorage.setItem("visibility", JSON.stringify(visibleOSes));
                } catch(err) {}
            }
        });

        $(".optionsSheet label, .optionsSheet input").on(click, function (e) { e.stopImmediatePropagation(); });

        $(".optionsSheet").on(click, function (e) {
            e.preventDefault();

            $(".optionsSheet .items")
                .css("z-index", "");

            $(".optionsSheet .cover")
                .one(kendo.support.transitions.event, function () {
                    if ($(this).parent().hasClass("k-state-opened")) {
                        $(".optionsSheet .items").css("z-index", 10);
                    }
                }).css("overflow");

            $(this).toggleClass("k-state-opened");
        });

        importWindow = $("#importWindow").kendoWindow({
            width: "400px",
            height: "400px",
            maxHeight: "400px",
            title: "Import Styles",
            visible: false,
            modal: true
        }).data("kendoWindow");

        exportWindow = $("#exportWindow");

        exportWindow.append('<br /><br /><a class="k-button" target="_blank" download="kendo.mobile.exported.css">Download CSS</a>');

        exportWindow = exportWindow.kendoWindow({
            width: "400px",
            height: "400px",
            maxHeight: "400px",
            title: "Export Styles",
            visible: false,
            modal: true
        }).data("kendoWindow");

        $("#resetStyles").on(click, function () {
            each(devices, function () {
                var that = this.toString();

                $("#" + that + "Device").data("kendoStyleEngine").reset();
            });
        });

        $("#importStyles").on(click, function () {
            if (sessionStorage && sessionStorage.length) {
                try {
                    $("#importWindow .k-textbox")[0].value = sessionStorage.getItem("import");
                } catch(err) {}
            }

            importWindow.center().open();
        });

        $("#exportStyles").on(click, function () {
            var output = "", blob = "", BlobBuilder,
                textarea = exportWindow.element.find("textarea"),
                anchor = exportWindow.element.find("a");

            each(devices, function () {
                var that = this.toString();
                if ($("#" + that + "box")[0].checked) {
                    output += $("#" + that + "Device").data("kendoStyleEngine").getFullCSS();
                }
            });

            textarea.text(output);
            try {
                blob = new Blob([output], {type: "text/plain"});
            } catch (e) {
                BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder;

                if (BlobBuilder) {
                    var bb = new BlobBuilder();
                    bb.append(output);

                    blob = bb.getBlob("text/plain");
                }
            }

            if (anchor[0].download) {
                anchor.attr("href", window.URL.createObjectURL(blob));
            } else {
                anchor.remove();
                textarea.css("height", "365px");
            }

            exportWindow.center().open();
        });

        $("#import").on(click, function () {
            var imports = $("#importWindow .k-textbox")[0].value.replace(/<\s*\/.*?>/gm, ""),
                stylesheet = $("<style scoped>" + imports + "</style>").appendTo(document.body),
                styles = {}, style;

            if (stylesheet[0].sheet) {
                each((stylesheet[0].sheet.rules || stylesheet[0].sheet.cssRules), function () {
                    deviceClasses.forEach(function (value) {
                        if (this.selectorText.indexOf(value) === 0) {

                            style = {};
                            for (var i = 0, len = this.style.length; i < len; i++) {
                                if (!style[this.selectorText]){
                                    style[this.selectorText] = {};
                                }
                                style[this.selectorText][this.style[i]] = this.style[this.style[i]] || this.style[$.camelCase(this.style[i])];
                            }

                            styles[value] = extend(styles[value], style);
                        }
                    }, this);
                });
            }

            for (var idx in styles) {
                var engine = $(idx).data("kendoStyleEngine");

                if (!$("#mixStyles")[0].checked) {
                    engine.object = {};
                }

                engine.populate(styles[idx]);

                for (i in styles[idx]) {
                    engine.store(i, styles[idx][i]);
                }
            }

            stylesheet.remove();

            try {
                sessionStorage.setItem("import", imports);
            } catch(err) {}

            importWindow.close();
        });

        window.tools = tools;
    })(jQuery);
} else {
    $(document.body).addClass("old-browser").show();
    $(".header, .tools, .files").hide();
    $(".box").empty().html("<span class='centered'><strong>The Kendo UI Mobile <span>ThemeBuilder</span></strong><span>is fully supported in WebKit based browsers and partially supported in Firefox.</span><br>Please use a compatible desktop browser.</span>")
}
